var jwt = require("jsonwebtoken");

var secret = "666666";

// var data = {
//     username:"guozenghui",
//     password:"abc123",
// }

var createToken = function(data){
    return jwt.sign(data,secret,{expiresIn:"2h"});
}

exports.createToken = createToken;

// token 解密

var decodeToken = function(token){
    return new Promise(function(resolve,reject){
        jwt.verify(token,secret,(err,data)=>{
            if(err){
                reject(err);
            }else{
                console.log(data);
                resolve(data);
            }
        })
    })
}

var checkToken = function(req,res,callback){
    var token = req.headers.token;
    if(token){
        decodeToken(token)
        .then(data=>{
            console.log(data);
            callback(data);
        })
        .catch(err=>{
            console.log(err);
            res.json({
                code:3200,
                msg:"token无效，请立即登录",
                err,
                type:0,
            })
        })
    }else{
        res.json({
            code:3200,
            msg:"token不存在，请立即登录",
            type:0,
        })
    }
}

exports.checkToken = checkToken